package com.jiangli.service.Search.Impl;



import com.jiangli.entity.Ingredient;
import com.jiangli.mapper.SearchHotMapper;
import com.jiangli.service.impl.IngredientServiceImpl;
import com.jiangli.utils.RedisLock;
import com.jiangli.utils.Sreach.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 候选词服务（用于编辑距离匹配）
 */
@Slf4j
@Service
public class IngredientCandidateServiceImpl{


    @Autowired
    private SearchHotMapper searchHotMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    private static final long CACHE_EXPIRE = 3600; // 1小时
    private static final String CANDIDATE_LOCK = "dish:candidate:lock";
    @Autowired
    private IngredientServiceImpl ingredientService;
    @Autowired
    private RedisLock redisLock;
    /**
     * 获取所有候选词（菜品名+热词）
     */

    public List<String> getAllCandidates() {
        // 先查Redis缓存
        Set<String> cacheCandidates = stringRedisTemplate.opsForSet().members(RedisKeyUtils.INGREDIENT_CANDIDATES);
        if (!CollectionUtils.isEmpty(cacheCandidates)) {
            return new ArrayList<>(cacheCandidates);
        }

        // 缓存未命中，查数据库
        return redisLock.executeWithLock(CANDIDATE_LOCK,
                ()->{
                    List<Ingredient> dishList = ingredientService.getAllIngredientWithCache();
                    List<String> dishNames = dishList.stream().map(Ingredient::getName).collect(Collectors.toList());
                    //List<String> hotWords = searchHotMapper.selectTopHotWords(200);

                    // 合并去重
                    List<String> allCandidates = new ArrayList<>(dishNames);
                    //if (!CollectionUtils.isEmpty(hotWords)) {
                    //allCandidates.addAll(hotWords);
                    //}
                    allCandidates = allCandidates.stream()
                            .filter(k -> k != null && !k.trim().isEmpty())
                            .distinct()
                            .collect(Collectors.toList());

                    // 存入缓存
                    if (!CollectionUtils.isEmpty(allCandidates)) {
                        stringRedisTemplate.opsForSet().add(
                                RedisKeyUtils.INGREDIENT_CANDIDATES,
                                allCandidates.toArray(new String[0])
                        );
                        stringRedisTemplate.expire(RedisKeyUtils.INGREDIENT_CANDIDATES, CACHE_EXPIRE, TimeUnit.SECONDS);
                    }
                    log.info("候选词{}", allCandidates.get(0));
                    return allCandidates;
                });

    }

    /**
     * 定时刷新候选词缓存（每天凌晨3点）
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void refreshCandidateCache() {
        stringRedisTemplate.delete(RedisKeyUtils.INGREDIENT_CANDIDATES);
        getAllCandidates();
    }
}